import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'DashboardHome',
        redirect: '/dashboard/qrcode'
      },
      {
        path: 'qrcode',
        name: 'QRCodeManagement',
        component: () => import('../views/QRCodeManagement.vue')
      },
      {
        path: 'qrcode/create',
        name: 'QRCodeCreate',
        component: () => import('../views/QRCodeCreate.vue')
      },
      {
        path: 'qrcode/edit/:id',
        name: 'QRCodeEdit',
        component: () => import('../views/QRCodeEdit.vue'),
        props: true
      },
      {
        path: 'category',
        name: 'QRCodeCategoryManagement',
        component: () => import('../views/QRCodeCategoryManagement.vue')
      },
      {
        path: 'decode',
        name: 'QRCodeDecode',
        component: () => import('../views/QRCodeDecode.vue')
      },
      {
        path: 'user',
        name: 'UserManagement',
        component: () => import('../views/UserManagement.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'user/edit/:id',
        name: 'UserEdit',
        component: () => import('../views/UserEdit.vue'),
        meta: { requiresAdmin: true },
        props: true
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('../views/Statistics.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory('/dist/'),
  routes
})

// 全局前置守卫
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 从本地存储获取用户信息
    const userStr = localStorage.getItem('user')
    const user = userStr ? JSON.parse(userStr) : null
    
    console.log('路由守卫检查用户:', user)
    
    if (!user) {
      // 未登录，重定向到登录页
      console.log('用户未登录，重定向到登录页')
      next({ name: 'Login', query: { redirect: to.fullPath } })
    } else {
      // 检查是否需要管理员权限
      if (to.matched.some(record => record.meta.requiresAdmin)) {
        console.log('检查管理员权限，用户角色:', user.role)
        if (user.role !== 'admin') {
          // 非管理员访问管理员页面，重定向到仪表盘
          console.log('非管理员访问管理员页面，重定向到仪表盘')
          next({ name: 'QRCodeManagement' })
          return
        }
      }
      // 已登录且有权限，放行
      console.log('用户已登录且有权限，放行')
      next()
    }
  } else {
    // 不需要认证的路由，直接放行
    next()
  }
})

export default router